$(function () {
    getDatumListData();

    initLayerDate("#lessonTime", false);
    var courseId = $("#courseId").val();
    $("body").on('click', '#createMaterial', function () {//创建素材
        initCreateMaterialWind(0, courseId, function (result) {//创建素材数据回调
            selectMaterialCallback(result);
        });
    }).on('click', '#selectMaterial', function () {//选择素材
        var subjectIds = $("#subjectIds").val();
        selectMaterial(2, courseId, 0, 'radio', subjectIds);
    }).on('click', '#uploadDatum', function () {//上传随堂资料
        var list = $("#datumList .del-datum-box");
        var maxNum = 1;
        if (list != null && list.length >=1) {
            icModale(0, '最可上传1个随堂资料');
            return;
        }
        maxNum = maxNum - list.length;

        //初始化文件上传窗口
        initUpdateFileWin({
            fileType: 'pdf',//文类类型["img","ico","xls","pdf","zip"]
            callback: 'uploadCallback',
            fileNumLimit: maxNum
        });
    }).on('click', '.del-datum-box', function () {
        $(this).parent().remove();
        getDatumListData();
    }).on('click', '#selectLorePoint', function () { // 选择考点
        var subject = $('#subjectIds').val();
        selectLoresetPoint(subject, 'radio', setLoresetPointData)
    }).on('click', '#selectQuestion', function () { // 选择试题
        var loresetPoint = $('#table-loreset-point tr[data-ids]');
        if (loresetPoint.length == 0) {
            icModale(0, '选择知识点');
            return;
        }
        loresetPoint = loresetPoint.map(function() {
            var ids = this.dataset['ids'];
            var index = ids.indexOf(',');
            return this.dataset['ids'].substr(index + 1);
        }).get().join(',');
        selectQuestion({
           'loresetPointIds': loresetPoint,
            'excludeSpecial':true
        });
    }).on('click', '#table-loreset-point i.fa-trash', function() { // 删除考点
        $(this).parents('tr[data-ids]').remove();
        toggleLoresetPointNoDataTips();
        $('#course-catalog-question tr[data-question]').remove();
        $('#course-catalog-question div.noDataTipsBox').parents('tr').toggleClass('hide', false);
    }).on('click', '#course-catalog-question i.fa-trash', function() { // 删除试题
        $(this).parents('tr[data-question]').remove();
        var length = $('#course-catalog-question tr[data-question]').length;
        $('#course-catalog-question div.noDataTipsBox').parents('tr').toggleClass('hide', length > 0);
    }).on('change','#nodeType',function () {//节点类型
        var nodeType = $(this).val();
        var catalogNameNode =    $("#catalogName");
        if(nodeType==1){
            catalogNameNode.next().text("章节名称 限30个字符以内");
            catalogNameNode.parents('.form-group').find('label>.catalog_name').text("章节名称");
            $("#node-type-2").addClass('hide');
        }else if(nodeType ==2){
            $("#node-type-2").removeClass('hide');
            var catalogNameNode =    $("#catalogName");
            catalogNameNode.next().text("节点名称 限30个字符以内");
            catalogNameNode.parents('.form-group').find('label>.catalog_name').text("节点名称");
        }
        $("input[name=nodeType]").val(nodeType);
    }).on('click', '#uploadVideo', function () {//上传视频的时间
        popupWindows();
    }).on('click','#selectVideo',function () {//选择音频、视频
        selectCommonVideo("VIDEO");
    }).on("ifChanged","#replay",function(){
        if($(this).is(':checked')){
            if(LiveType == 'CC'){
                $("#backCodeOne").removeClass("hide");
                $("#backCodeTwo").removeClass("hide");
            }else{
                $("#backCodeThree").removeClass("hide");
                $("#backCodeFour").removeClass("hide");
            }
        }else {
            if(LiveType == 'CC'){
                $("#backCodeOne").addClass("hide");
                $("#backCodeTwo").addClass("hide");
            }else{
                $("#backCodeThree").addClass("hide");
                $("#backCodeFour").addClass("hide");
            }
            $('input[name="backCode"]').val("");
             var select =   document.getElementById("backUrl");
             if(select!=null&&select!=undefined&&select.length>0){
                select.options[0].selected = true;
                 $("input[name='liveId']").val(" ");
                 $("input[name='playbackId']").val(" ");
            }
        }
    }).on("change","#backUrl",function(){
        var selected = $("#backUrl option:selected");
        var playUrl = $(this).val().replace("http://", "https://");
        $('input[name="backCode"]').val(playUrl);
        var liveId = selected.data('live');
        if (liveId == '' || liveId == null) {
            liveId = " ";
        }
        var playbackId = selected.data('playback');
        if (playbackId == '' || playbackId == null) {
            playbackId = " ";
        }
        $("input[name='liveId']").val(liveId);
        $("input[name='playbackId']").val(playbackId);
    });

    //监听选择试题回调
    window.addEventListener('event-select-admin-question-list', function (evt) {
        var questionList = evt.detail.questionList;
        $('#course-catalog-question div.noDataTipsBox').parents('tr').toggleClass('hide', questionList.length > 0);
        questionList.forEach(function (v) {
            if ($('tr[data-question=' + v.id + ']').length == 0) {
                var tr = '<tr data-question="' + v.id + '" data-score="' + v.score + '">' +
                    '<td class="text-center">' + v.id + '</td>' +
                    '<td class="text-center">' + v.name + '</td>' +
                    '<td class="text-center">' +
                    '<a href="javascript:void(0)" class="ml5"><i class="fa fa-trash"></i></a>' +
                    '</td>' +
                    '</tr>';
                $('#course-catalog-question').append(tr);
            }
        });
    });

    /**
     * 表格设置考点数据
     * @param array
     */
    function setLoresetPointData(array) {
        if (Array.isArray(array)) {
            array.forEach(function (v) {
                $('#table-loreset-point tr[data-ids]').remove();
                var html = '<tr data-id="' + v.id + '" data-ids="' + v.ids + '">' +
                    '<td class="text-center">' + v.name + '</td>' +
                    '<td class="text-center"><a href="javascript:void(0)"><i class="fa fa-trash"></i></a></td>' +
                    '</tr>';
                $(html).insertAfter($('#table-loreset-point tr.jqgfirstrow'));
            });
            toggleLoresetPointNoDataTips();
        }
    }

    /**
     * 切换无考点提示
     */
    function toggleLoresetPointNoDataTips() {
        if ($('#table-loreset-point').find('tr').length == 2) {
            $('#table-loreset-point').find('div.noDataTipsBox').parents('tr').removeClass('hide');
        } else {
            $('#table-loreset-point').find('div.noDataTipsBox').parents('tr').addClass('hide');
        }
    }
    function popupWindows() {
        var type = 1;
        var  message='请选择要上传的视频文件';

        index = parent.layer.open({
            type: 2,
            area: ['500px', '100px'],
            content: baseloaction +'/admin/liveToV/create/initVideoUploadPage?type='+type,
            shadeClose: false,
            shade: [0.3, '#000'],
            title: '<strong>'+message+'</strong>'
        });
        setMethods(callbackClose);
    }
//回调关闭上传素材资源时的公共弹窗
    callbackClose = function (){
        parent.layer.close(index);
    };

});
var close =null;
function setMethods (to){
    close =to;
};
/**
 * 获取随堂资料数据
 */
function getDatumListData() {
    var list = $(".datum-li-box");
    if (list == null || list.length <= 0) {
        $("input[name='datums']").val('');
    } else {
        var arr = new Array();
        $.each(list, function (index, em) {
            var obj = {'name': $(em).data('name'), 'url': $(em).data('url')};
            arr.push(obj);
        });
        var data = JSON.stringify(arr);
        data = encodeURIComponent(data);
        $("input[name='datums']").val(data);
    }
}

/**
 * 上传回调
 * @param data
 */
function uploadCallback(data) {
    $("#not-datum").remove();
    var name = data.fileName;
    var url = data.url;
    var context = '<li class="list-group-item datum-li-box" data-name="' + name + '" data-url="' + url + '">';
    context += '<span class="fs12">&nbsp;&nbsp;' + name + '</span>';
    context += '<span style="cursor: pointer;" data-original-title="删除" data-placement="left" data-toggle="tooltip" class="fs12 pull-right del-datum-box">';
    context += '<i class="fa fa-close"></i></span></li>';
    $("#datumList").append(context);
    getDatumListData();
}

/**
 * 选择素材回调
 * @param material
 */
function selectMaterialCallback(material) {
    $("input[name='materialId']").val(material.id);
    var catalogName = $("#catalogName").val();
    if ($.trim(catalogName) == '') {
        $("#catalogName").val(material.name);
    }
    if (material.videoDuration){
        $("#videoDuration").val(material.videoDuration)
    }else{

    }
    $("#materialList").html('<li class="list-group-item"><span class="fs12">&nbsp;&nbsp;' + material.name + '</span></li>');
    $("input[name='materialTypeKey']").val(material.typeKey);
    if (material.typeKey == 'VIDEO' || material.typeKey == 'AUDIO') {
        $("#audition-box").removeClass("hide");
    } else {
        $("#audition-box").addClass("hide");
    }

    if (material.typeKey == 'LIVE') {
        $("#lessontime-box").addClass("hide");
        $("#lessonStartTime").val(material.liveBeginTime);
        $("#lessonEndTime").val(material.liveEndTime);
        $("#live-time-box").removeClass("hide");

    } else {
        $("#live-time-box").addClass("hide");
        $("#lessontime-box").removeClass("hide");
    }
    if (material.typeKey == 'ARTICLE') {
        $("#article-box").removeClass("hide");
        $("#articleSummary").html(material.articleSummary);
        $("#articleContext").html(material.articleContext);
    } else {
        $("#article-box").addClass("hide");
    }
}

//96k 资源上传回调
parent.window.addEventListener('message', function (response) {
    if (!$.isEmptyObject(response)) {
        $('input[name="backCode"]').val(response.data.msg);
        close();
    }
}, false);

/**
 * 选择回调
 * @param video
 */
function selectVideoCallback(video) {
    debugger
    $('input[name="backCode"]').val(video.code);
}